package com.zm.exam.springbootexam.biz;


import com.zm.exam.springbootexam.entry.Exam;
import com.zm.exam.springbootexam.entry.ExamDetail;
import com.zm.exam.springbootexam.entry.Question;
import com.zm.exam.springbootexam.mapper.ExamDetailMapper;
import com.zm.exam.springbootexam.mapper.ExamMapper;
import com.zm.exam.springbootexam.mapper.QuestionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ExanBiz {
    @Autowired
    ExamMapper examMapper;
    @Autowired
    ExamDetailMapper examDetailMapper;
    @Autowired
    QuestionMapper questionMapper;

    @Transactional
    public void commit(Exam exam){
        //查询题目信息
        //统计分数
        int sum = 0;
        for (ExamDetail detail : exam.getDetails()){
            Question question = questionMapper.selectById(detail.getQid());
            String[] items = question.getItems().split(";");
            String[] answers = detail.getAnswer().split(";");
            detail.setTf(0);
            if ("填空题".equals(question.getType())){
                for (int i = 0; i < items.length; i++) {
                    System.out.println("detail.getTf() = " + detail.getTf());
                    System.out.println("items[i] = " + items[i]);
                    System.out.println("answers[i] = " + answers[i]);
                    detail.setTf(detail.getTf()+(items[i].equals(answers[i])?1:0));
                }
                if (detail.getTf()>0){
                    sum += detail.getTf() * 2;
                }
            }else if(question.getType().endsWith("选题")){
                boolean isTrue = true;
                for (int i = 0; i < items.length; i++) {
                    if (items[i].startsWith("$")) {
                        items[i] = items[i].substring(1);
                    }else {
                        items[i] = " ";
                    }
                    if(items[i].equals(answers[i]) == false){
                        isTrue = false;
                        break;
                    }
                }
                if (isTrue){
                        sum += "单选题".equals(question.getType()) ? 3 : 5;
                        detail.setTf(1);
                }else {
                    detail.setTf(0);
                }
            }else {
                detail.setTf(question.getItems().equals(detail.getAnswer())?1:0);
                if (detail.getTf()==1){
                    sum+=1;
                }
            }
        }

        exam.setScore(sum);
        examMapper.insert(exam);
        for (ExamDetail examDetail : exam.getDetails()) {
            examDetail.setEid(exam.getId());
            examDetailMapper.insert(examDetail);
        }

    }


}
